var jQT = new $.jQTouch({
    icon: '/images/icon.png',
    addGlossToIcon: true,
    startupScreen: '/images/startup.png',
    statusBar: 'black',
    preloadImages: ['/jqt/themes/jqt/img/button.png',
                    '/jqt/themes/jqt/img/back_button.png',
                    '/jqt/themes/jqt/img/back_button_clicked.png',
                    '/images/plus_circle.png']
});

function updateCurrentSong(data) {
    var html;
    if(data.message) {
    	html = $('<span>').html(data.message).html();
    	srcImage = '';
    	} else {
    	html = $('<span>').html(data.song.artist + '<br/>' + data.song.title + '<br/>' + data.song.album).html();  
    	srcImage = '/images/cover/' + data.song.cover;  	
    }
    
    if ($('#coverImage').attr('src') != srcImage) {
    	$('#coverImage').attr('src', srcImage);
    }
    
    if ($('#currentSong').html() != html) {
        $('#currentSong').html(html);
    }
}

function searchAlbum(searchString) {
	searchString = $.trim(searchString);
	$.ajax({
		type: 'POST',
		url: '/albums/' + searchString,
		dataType: 'json',
		success: function(data) { 
			updateAlbumList(data);
			$('#album-name-text').val('').blur();
			},
    	error: function(request, status, errorThrown) {
          	   showError();
          	}
	});
}

function isChar(Data) {
	varChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var isChar = true;
	var index = 0;
	while ((index < Data.length) && (isChar)) {
		isChar = (varChars.indexOf(Data.charAt(index)) != -1);
		index++;
	}
	return isChar;
}

function updateAlbumList(data) {
	$('#album-name-results').html('');
	var lista = '';	
	var startsWith = '';
	$.each($(data.albums), function(index, value) {		
		var albumId = value.id.replace(/=/g, /-/);
		var currentStartsWith = value.title.substring(0,1).toUpperCase()
		if (!isChar(currentStartsWith)) { currentStartsWith = '#' }
		if (startsWith != currentStartsWith){
			startsWith = currentStartsWith;
			lista += '<li id="' + startsWith + '" class="sep">' + startsWith + '</li>';
		}
		lista += '<li id="' + albumId + '" class="albumName">' + value.title + '</li>';
	});
	$('#album-name-results').html(lista);
	$('.albumName').click(function() {
        $.ajax({
            type: 'POST',
            url: '/songs/' + $(this).attr('id'),
            dataType: 'json',
            success: function(data) { updateSongList(data); jQT.goTo('#songList', 'slideleft'); }
          });
	});
	jQT.setPageHeight();
	$('#albumList').removeData("listIndex");
	$('.listIndex').remove();
	initListIndex();
}

function updateSongList(data) {
	$('#songs-in-album').html('');
	$('<li/>').addClass('sep').attr('id','titulo').text(data.songs[0].album).appendTo('#songs-in-album');	
	$.each($(data.songs), function(index, value) {
		var songId = value.id.replace(/=/g, /-/);
		$('<li/>').addClass('songName').attr('id', songId).text(value.title).click(function() {
            $.ajax({
                type: 'POST',
                url: '/queue/play/' + value.id,
                success: function(data) { jQT.goTo('#playerControls', 'slideleft')},
                dataType: 'json'
              });
		}).appendTo('#songs-in-album');		
	});
	jQT.setPageHeight();
}

function updatePlaylistData(data) {
	$('#playlist-results').html('');
	$.each(data.playlists, function (index, value) {
		$('<li/>').addClass('playlistItem').text(value.name).appendTo('#playlist-results').click(function() {
			$.ajax({
				type: 'POST',
				url: '/playlist/' + value.id,
				success: function(data) {
					updateCurrentSong(data); 
					jQT.goTo('#playerControls', 'slideleft');
				},
				dataType: 'json'
			});
		});
	});
}

function selectPlayer(service){
    $('#album-name-results').text('');
    $('#currentSong').text('Player selection unsuccessful. Please go back and retry.');
    $.ajax({
        type: 'POST',
        url: '/player/' + service,
        success: function(data) { 
                        updateCurrentSong(data);
                        getShuffle();
                        jQT.goTo('#playerControls', 'slideleft');
                    },
        error: function(request, status, errorThrown) {
                 	   showError();
                 	   },
        dataType: 'json'
    });    
}

function updatePlayers(firstRun) {
	$.ajax({
		type: 'POST',
		url: '/player/list',
		dataType: 'json',
		success: function(data) { 
			if (data.players.lenght = 1 && firstRun){
				selectPlayer(data.players[0].service);
			} else {	
				$('#players-result').html('');
				$.each(data.players, function (index, value) {
					$('<li/>').addClass('playerSelect').text(value.name).click(function () {
						selectPlayer(value.service);
					}).appendTo('#players-result');
				});
			}
		}
	});

}

function showError() {
    $('#currentSong').text('Error getting data from server');
}

$.timer(20000, function (timer) {
    $.ajax({
          type: 'POST',
          url: '/stats/currentSong',
          success: function(data) { updateCurrentSong(data); },
          error: function(request, status, errorThrown) {showError();},
          dataType: 'json'
    });
});

function getShuffle() {
	$.ajax({
		type: 'POST',
		url: '/random/get',
		success: function(data){
			$('#randomToggle').attr('checked', data.random);
			},
		error: function(request, status, errorThrown) {showError();},
		dataType: 'json'
	});
}

$(document).ready(function(e){
    $('#playerSelect').bind('pageAnimationStart', function(event, info){
    	if (info.direction == "in"){    		
    		updatePlayers(false);
    	}
    });
    
    $('#playlistList').bind('pageAnimationStart', function(event, info){
    	if (info.direction == "in"){  
	    	$.ajax({
	    		type: 'POST',
	    		url: '/playlist',
	    		dataType: 'json',
	    		success: function(data) { updatePlaylistData(data);}
	    	});
    	}
    });
    
    $('#albumList').bind('pageAnimationStart', function(event, info){
    	if (info.direction == "in"){  
    		searchAlbum('');
    	}
    });
    
});

$(function() {
	
	//Update list of players
	updatePlayers(true);
	
	//By default, start with upper controls hidden
	$('#upperControls').hide();
	
    $.each($('#playback img.control'), function(index, value) {
        $(value).click(function() {
        	$(value).addClass('clicked');
            $.ajax({
              type: 'POST',
              url: '/playback/' + $(this).attr('rel'),
              success: function(data) { updateCurrentSong(data); $(value).removeClass('clicked'); },
              error: function(request, status, errorThrown) {showError();},
              dataType: 'json'
            });
        });
    });
    
    $.each($('#volume img.control'), function(index, value) {
        $(value).click(function() {
        	$(value).addClass('clicked');
            $.ajax({
              type: 'POST',
              url: '/volume/' + $(this).attr('rel'),
              error: function(request, status, errorThrown) {showError(); },
              success: function(data) { $(value).removeClass('clicked'); },
              dataType: 'json'
            });
        });
    });
    
    $.each($('#seek img.control'), function(index, value) {
        $(value).click(function() {
        	$(value).addClass('clicked');
            $.ajax({
              type: 'POST',
              url: '/seek/' + $(this).attr('rel'),
              error: function(request, status, errorThrown) {showError(); },
              success: function(data) { $(value).removeClass('clicked'); },
              dataType: 'json'
            });
        });
    });
    
    $('#randomToggle').change(function(){
    	$(this).addClass('clicked');
    	$.ajax({
    		type: 'POST',
    		url: '/random/set',
    		error: function(request, status, errorThrown) {showError(); },
    		success: function(data) { 
			    $('#randomToggle').removeClass('clicked');
    			$('#randomToggle').attr('checked', data.random);
    			},
    		dataType: 'json'
    	});
    });
    
    $('#coverart').click( function(){
    	$('#upperControls').toggle();
    });
    
    $('#album-name-text').change(function() {
    	searchAlbum($.trim($(this).val()));
    });
});
